<template>
  <div class="register-container">
    <!-- 注册容器 -->
    <el-card class="register-card">
      <!-- 注册卡片 -->
      <h2 class="register-title">注册</h2>
      <!-- 表单组件，绑定表单引用、模型和验证规则 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        @keyup.enter="handleRegister"
      >
        <!-- 用户名输入项 -->
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>

        <!-- 邮箱输入项 -->
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
          />
        </el-form-item>

        <!-- 密码输入项 -->
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <!-- 确认密码输入项 -->
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            class="register-btn"
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册页面底部链接 -->
      <div class="register-footer">
        <span>已有账号？</span>
        <el-link type="primary" @click="goToLogin">立即登录</el-link>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入必要的模块和组件
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { register } from '@/api/auth'

// 初始化路由实例
const router = useRouter()

// 表单引用对象，用于手动触发验证
const registerFormRef = ref<FormInstance>()
// 按钮加载状态
const loading = ref(false)

// 注册表单数据模型
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 用户名验证函数
const validateUsername = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入用户名'))
  } else if (value.length < 2) {
    callback(new Error('用户名长度不能小于4位'))
  } else {
    callback()
  }
}

// 邮箱格式验证函数
const validateEmail = (rule: any, value: string, callback: any) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!value) {
    callback(new Error('请输入邮箱'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入有效的邮箱地址'))
  } else {
    callback()
  }
}

// 密码验证函数
const validatePassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'))
  } else {
    callback()
  }
}

// 确认密码一致性验证
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则配置
const registerRules = ref<FormRules>({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }]
})

// 注册处理函数
const handleRegister = async () => {
  try {
    // 触发表单验证
    await registerFormRef.value?.validate()
    loading.value = true

    // 调用注册接口
    try {
      await register({
        username: registerForm.value.username,
        email: registerForm.value.email,
        password: registerForm.value.password
      })

      // 成功提示并跳转至登录页
      ElMessage.success('注册成功')
      router.push('/login')
    } catch (error) {
      // 错误提示
      ElMessage.error(error.response?.data?.message || '注册失败')
    } finally {
      // 结束加载状态
      loading.value = false
    }
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
/* 页面整体布局 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 注册卡片样式 */
.register-card {
  width: 400px;
  padding: 20px;
}

/* 标题样式 */
.register-title {
  text-align: center;
  margin-bottom: 20px;
}

/* 按钮宽度 */
.register-btn {
  width: 100%;
}

/* 底部链接样式 */
.register-footer {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}
</style>
